local app = require "app"
local gamelib = require "club.threecard.gamelib"
local egame_stage = gamelib.require("game_scene.egame_stage")
local coroutine = gamelib.coroutine

local log = gamelib.logging.get("game_scene")

local game_scene = 
{
    loaded = false,
    stage = egame_stage.empty;
    room_config_id = -1;
}

local temp_fields = {}

function game_scene.init()
end

function game_scene.release()
    for k, v in pairs(temp_fields) do
        temp_fields[k] = nil
    end
    game_scene.loaded = false
end

-- 开始进入游戏场景
function game_scene.enter(room_config_id)
    local stage = game_scene.stage;
    if stage == egame_stage.on_enter
    or stage == egame_stage.on_entered
    or stage == egame_stage.ingame then
        log.warn("当前游戏状态："..stage);
        return;
    end

    game_scene.room_config_id = room_config_id or app.store.avatar.state.room_config_id;
    coroutine.start(function()
        game_scene.stage = egame_stage.on_enter;
        gamelib.game_scene.internal_entrances.on_befor_enter();
        gamelib.game_scene.entrances.on_befor_enter();

        gamelib.game_scene.internal_entrances.on_enter();
        gamelib.game_scene.entrances.on_enter();

        game_scene.stage = egame_stage.on_entered;
        gamelib.game_scene.internal_entrances.on_entered();
        gamelib.game_scene.entrances.on_entered();
        game_scene.loaded = true
        game_scene.stage = egame_stage.ingame;
    end)
end

-- 离开游戏场景
function game_scene.leave()
    coroutine.start(function()
        game_scene.stage = egame_stage.on_exit;
        gamelib.game_scene.internal_entrances.on_befor_exit();
        gamelib.game_scene.entrances.on_befor_exit();

        gamelib.game_scene.internal_entrances.on_exit();
        gamelib.game_scene.entrances.on_exit();

        game_scene.stage = egame_stage.on_exited;
        gamelib.game_scene.internal_entrances.on_exited();
        gamelib.game_scene.entrances.on_exited();

        game_scene.stage = egame_stage.empty;
        game_scene.room_config_id = -1;
    end)
end

-- 重写入口需求
function game_scene.overried_entrance(e)
    local entrances = gamelib.game_scene.entrances;
    for k, v in pairs(entrances) do
        if e[k] then
            entrances[k] = e[k];
        end
    end
end

local mt = 
{
    __index = function(t, key)
        local ret = temp_fields[key]
        if ret then
            return ret
        end

        ret = gamelib.require("game_scene."..key)
        if ret then
            rawset(t, key, ret)
        end

        return ret;
    end,

    __newindex = function(t, key, value)
        temp_fields[key] = value
    end
}

return setmetatable(game_scene, mt)